package WWTPAgent;

import jade.content.ContentElement;
import jade.content.ContentManager;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.WakerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import wwtp.ontology.SendWater;
import wwtp.ontology.Water;
import DataBases.DirectWaterObject;

public class WWTPInflowWaterBehaviour extends CyclicBehaviour{

	protected MessageTemplate mt;
	protected ContentManager manager;

	@Override
	public void action() {
		// TODO Auto-generated method stub
		mt = MessageTemplate.and(MessageTemplate.MatchConversationId("Water"),MessageTemplate.MatchPerformative(ACLMessage.INFORM));
		manager = myAgent.getContentManager();
		final ACLMessage msg = myAgent.receive(mt);
        if (msg!=null){
    		try{
    		 	ContentElement ce = manager.extractContent(msg);
	   			if(ce instanceof SendWater){
	   				DirectWaterObject dwo = ((WWTPAgent)myAgent).dbDirectWater.exists (msg.getSender().getLocalName(), myAgent.getLocalName());
	   				Water w = ((SendWater)ce).getWater();
	   				myAgent.addBehaviour(new WakerBehaviour(myAgent,dwo.getTiempoDeTransito()) {

						@Override
						protected void handleElapsedTimeout() {
							// TODO Auto-generated method stub
							//System.out.println(myAgent.getLocalName() + " water recieved");
							myAgent.addBehaviour(new WaterTreatmentBehaviour(msg));
						}
					});
	    		}

    		}
   			catch (Exception e) {
   				e.printStackTrace();
   			}
        } else {
        	block();
        }
	}

}
